/**
 * Copyright (c) 2019, ShangHai YTO Co., Ltd.
 * All right reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF YTO
 * CO., LTD.  THE CONTENTS OF THIS FILE MAY NOT BE DISCLOSED
 * TO THIRD PARTIES, COPIED OR DUPLICATED IN ANY FORM, IN WHOLE OR IN PART,
 * WITHOUT THE PRIOR WRITTEN PERMISSION OF YTO
 * CO., LTD.
 */
package org.sc.xl.easyexcel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.ImageData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;

import javax.imageio.ImageIO;
import java.io.ByteArrayInputStream;

/**
 * @description: TODO 请在此添加描述
 * @reason: TODO ADD REASON(可选)
 * @author FXL
 *
 * @date 2024/10/20 21:50 
 * @since JDK 1.8
 */
public class CustomModifyHandler implements CellWriteHandler {


    // 256分之一的字符宽度转换为标准字符宽度。
    public static Integer standardCharacterWidth = 256;

    // 7.5是一个估算的字符到像素的转换因子
    public static Float character2PixelFactor = 7.5f;

    // 将点转换为英寸，因为1点 = 1/72英寸。
    public static Integer pixel2InchFactor = 72;

    // 英寸转换为像素，其中96是常用的DPI（每英寸像素数）值。
    public static Integer dpi = 96;

    // 行高与像素的转换因子
    public static Float rowHeight2PixelFactor = 1.3333f;

    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        if (null == cellData || CollectionUtils.isEmpty(cellData.getImageDataList())) {
            return;
        }
        Sheet sheet = cell.getSheet();
        if (writeSheetHolder.getHead().size() - 2 == cell.getColumnIndex()) {
            //箭头列
            ImageData imageData = cellData.getImageDataList().get(0);
            // 处理图像缩放 - 等比例缩放
            ByteArrayInputStream bis = null;
            try {
                bis = new ByteArrayInputStream(imageData.getImage());
                java.awt.image.BufferedImage image = ImageIO.read(bis);
                int targetWidth = (int) (sheet.getColumnWidth(cell.getColumnIndex()) / standardCharacterWidth * character2PixelFactor);
                int targetHeight = (int) (cell.getRow().getHeightInPoints() / pixel2InchFactor * dpi);

                // 计算图像的缩放比例
                double scaleX = (double) targetWidth / image.getWidth();
                double scaleY = (double) targetHeight / image.getHeight();
                double scale = Math.min(scaleX, scaleY);

                // 计算缩放后的图像大小
                int scaledWidth = (int) (image.getWidth() * scale);
                int scaledHeight = (int) (image.getHeight() * scale) - 5;

                // 计算上下左右四个角的空白
                int topPadding = (targetHeight - scaledHeight) / 2;
                int bottomPadding = targetHeight - scaledHeight - topPadding;
                int leftPadding = (targetWidth - scaledWidth) / 2;
                int rightPadding = targetWidth - scaledWidth - leftPadding;

                // 行高（点）= 像素高度 / 1.3333
                imageData.setTop((int) (topPadding / rowHeight2PixelFactor));
                imageData.setBottom((int) (bottomPadding / rowHeight2PixelFactor));
                imageData.setLeft((int) (leftPadding / rowHeight2PixelFactor));
                imageData.setRight((int) (rightPadding / rowHeight2PixelFactor));
                bis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        CellWriteHandler.super.afterCellDataConverted(writeSheetHolder, writeTableHolder, cellData, cell, head, relativeRowIndex, isHead);
    }
}
